using System;
using System.Diagnostics;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.WowAddonStudio.FrameXml.Components;
using Microsoft.WowAddonStudio.FrameXml.Editor.ToolWindows;
using Microsoft.WowAddonStudio.Services;

namespace Microsoft.WowAddonStudio.FrameXml.Editor
{
	/// <summary>
	/// 
	/// </summary>
	public class LayoutControllerService : ILayoutControllerService
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="LayoutControllerService"/> class.
		/// </summary>
		/// <param name="provider">The <see cref="IServiceProvider"/> parameter.</param>
		public LayoutControllerService(IServiceProvider provider)
		{
			ServiceProvider = provider;
		}

		/// <summary>
		/// Gets or sets the service provider.
		/// </summary>
		/// <value>The service provider.</value>
		public IServiceProvider ServiceProvider { get; set; }

		/// <summary>
		/// Display Layout Control ToolWindow in environment.
		/// </summary>
		public void ShowLayoutControl()
		{
			try
			{
				var window = (ToolWindowPane) ServiceProvider.GetService(typeof (LayoutControllerToolWindow));
				var windowFrame = (IVsWindowFrame) window.Frame;

				var manager = (ILayoutControlManager) ServiceProvider.GetService(typeof (ILayoutControlManager));

				if (manager != null)
					manager.Resume();

				ErrorHandler.ThrowOnFailure(windowFrame.Show());
			}
			catch (Exception ex)
			{
				Trace.WriteLine("ShowLayoutControl exception: " + ex);
			}
		}

        /// <summary>
        /// Switches to Edit mode usnig the control.
        /// </summary>
        /// <param name="control">The control.</param>
        public void EditControl(object control)
        {
            var frameXmlControl = control as IFrameXmlControl;
            if (frameXmlControl != null)
            {
                var manager = (ILayoutControlManager)ServiceProvider.GetService(typeof(ILayoutControlManager));
                if (manager != null)
                    manager.Edit(frameXmlControl);
            }
        }
	}
}